<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" :title="showTitle">
      <van-icon slot="left" name="arrow-left" @click="back" />
    </van-nav-bar>
    <van-tabs ref="tabs" color="#3296fa" v-model="active" @click="change">
      <van-tab title="登录" name="login">
        <van-form ref="loginForm" @submit="login" label-width="66">
          <van-field
            v-model="user.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="rules.username"
            maxlength="10"
          />
          <van-field
            v-model="user.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="rules.password"
            maxlength="16"
          />
          <div class="button">
            <van-button round block type="info" native-type="submit">登录</van-button>
          </div>
        </van-form>
      </van-tab>

      <van-tab title="注册" name="register">
        <van-form ref="registerForm" @submit="register" label-width="66">
          <van-field
            v-model="user.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="rules.username"
            maxlength="10"
          />
          <van-field
            v-model="user.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="rules.password"
            maxlength="16"
          />
          <van-field
            v-model="repassword"
            type="password"
            name="repassword"
            label="确认密码"
            placeholder="请输入密码"
            :rules="rules.repassword"
            maxlength="16"
          />
          <div class="button">
            <van-button round block type="info" native-type="submit">注册</van-button>
          </div>
        </van-form>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { login, register, getUserInfo, initFollow } from '@/api/user'
import { TOKEN_KEY } from '@/utils/config'
import Follows from '@/api/constant/follows'

export default {
  name: 'Login',
  components: {},
  props: {},
  data () {
    const validateUsername = async value => {
      try {
        const userInfo = await getUserInfo({ username: this.user.username })
        if (userInfo.username === value) {
          this.$toast.fail('用户名已存在')
          return false
        }
      } catch (error) {
        console.log(error)
      }
    }
    const validatePwd = value => value === this.user.password

    return {
      Follows,
      active: 'login',
      user: {
        username: '',
        password: ''
      },
      repassword: '',
      rules: {
        username: [
          { required: true, message: '用户名不能为空' },
          { pattern: /^[\S]{0,10}$/, message: '用户名不能超过10位' },
          { validator: validateUsername, message: '用户名已存在' }
        ],
        password: [
          { required: true, message: '密码不能为空' },
          { pattern: /^[\S]{6,16}$/, message: '密码格式不正确, 长度6-16位' }
        ],
        repassword: [
          { required: true, message: '确认密码不能为空' },
          { validator: validatePwd, message: '两次密码不一致' }
        ]
      }
    }
  },
  computed: {
    showTitle () {
      return this.active === 'login' ? '登录' : '注册'
    }
  },
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async login () {
      try {
        await this.$refs.loginForm.validate()
        this.$toast.loading({
          message: '登录中...', // 展示时的提示信息
          forbidClick: true, // 展示时, 静止点击背景
          duration: 0 // toast 展示时间 默认为2秒, 0 表示持续展示
        })
        const res = await login(this.user)
        this.$store.commit('setUser', res)
        this.$toast.success('登录成功')
        this.back()
      } catch (error) {
        console.log('登录失败: ', error)
        this.$toast.fail('登录失败')
      }
    },
    async register () {
      try {
        await this.$refs.registerForm.validate()
        this.$toast.loading({
          message: '注册中...', // 展示时的提示信息
          forbidClick: true, // 展示时, 静止点击背景
          duration: 0 // toast 展示时间 默认为2秒, 0 表示持续展示
        })
        this.user.token = TOKEN_KEY + '_' + this.user.username.toUpperCase()
        await register(this.user)
        let userInfo = await getUserInfo()
        userInfo = userInfo[userInfo.length - 1]
        await initFollow({ id: userInfo.id, userId: userInfo.id, ...Follows })
        this.$toast.success('注册成功')
        this.active = 'login'
      } catch (error) {
        console.log('注册失败: ', error)
        this.$toast.fail('注册失败')
      }
    },
    change () {
      this.user = { username: '', password: '' }
      this.repassword = ''
      if (this.active === 'login') {
        this.$refs.loginForm && this.$refs.loginForm.resetValidation()
      } else {
        this.$refs.registerForm && this.$refs.registerForm.resetValidation()
      }
    },
    // 解决back跳转的问题
    back () {
      this.$router.beforeEach((to, from, next) => {
        if (to.path === '/user/personal' && from.path === '/login') {
          // return this.$router.push('/my')
          return this.$router.go(-1)
        }
        next()
      })
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  /deep/ .van-tabs__nav--card {
    margin: 0 !important;
  }
  .button {
    margin: 16px;
  }
}
</style>
